import {Component, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {TrainService} from "@train/train.service";
import {TrainClassroomScheme, TrainClassScheduleVO, TrainSubjectCommentListVO, TrainTeacherVO} from "@interface/index";
import {ParentService} from "@train/parent/parent.service";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {TabModal} from "@shared/components/tab/tab/tab.modal";
import {ImageServeService} from "@shared/service/image/image-serve.service";
import {PlanService} from "@train/plan/plan.service";
import {ToolsService} from "@shared/service/tools/tools.service";
import {Title} from "@angular/platform-browser";
import {AuthService} from "@shared/service/auth/auth.service";

@Component({
  selector: 'seed-class-detail',
  templateUrl: './class-detail.component.html',
  styleUrls: ['./class-detail.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ClassDetailComponent implements OnInit {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  public lessons: Array<TrainSubjectCommentListVO> = [];
  public className: '';
  public tabArray = [];
  public tabType = 'teacherComment';
  public teacherIndex = 0;
  public curTeacherInfo: TrainTeacherVO;
  public teachers: Array<TrainTeacherVO> = [];
  public teacherCommentInfo = {
    classId: 0,
    studentId: 0,
    page: 1,
    rows: 10
  };

  // 教学计划
  public tabs: Array<TabModal>;
  public classId: number;
  public teachScheme: TrainClassroomScheme;
  public classSchedule: Array<TrainClassScheduleVO>;
  public  defaultIcon = '';
  constructor(
    private activatedRoute: ActivatedRoute,
    private router: Router,
    private trainService: TrainService,
    private parentService: ParentService,
    private _imgService: ImageServeService,
    private _titleService: Title,
    private _palnService: PlanService,
    private _authService: AuthService,
    public toolService: ToolsService,
    private imgService: ImageServeService
  ) {
    this.tabs = [
      {title: '学情分析', content: '暂无内容', tag: 'analysis', isShow: false, hasExtend: false, shortContent: ''},
      {title: '学习目标', content: '暂无内容', tag: 'target', isShow: false, hasExtend: false, shortContent: ''},
      {title: '教学措施', content: '暂无内容', tag: 'measure', isShow: false, hasExtend: false, shortContent: ''}
    ];

    let lessonTabs = [{
      type: 'teacherComment',
      name: '教练点评'
    }, {
      type: 'teachPlan',
      name: '教学计划'
    }, {
      type: 'teacherInfo',
      name: '教练信息'
    }];

    this.activatedRoute.queryParams.switchMap((param: Params) => {
      this.className = param['className'];
      param['courseType'] === '2' && lessonTabs.splice(1, 1);
      this.tabArray = lessonTabs;
      return this.activatedRoute.params;
    }).subscribe((param: Params) => {
      this.teacherCommentInfo.classId = param['classId'];
      this.classId = param['classId'];
      this.teacherCommentInfo.studentId = param['studentId'];
      this.getLessonListForParent();
      this.defaultIcon = this.imgService.getMiddleArticleImgHolder();
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 查询课时列表（家长）
   */
  getLessonListForParent() {
    const {classId, studentId, page, rows} = this.teacherCommentInfo;
    const params = {
      classId: classId,
      studentId: studentId,
      page: page,
      rows: rows
    };
    this.trainService.getLessonListForParent(params).subscribe((res) => {
      if (res.result === '0' && res.data) {
        const result = res.data;
        const lessons = result.list;
        this.teacherCommentInfo.page++;
        this.infiniteScroll.complete();
        this.lessons = [...this.lessons, ...lessons];
        if (!result.hasNextPage) {
          this.infiniteScroll.enable(false);
        }
      }
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 切换tab
   */
  chooseTab(type) {
    this.tabType = type;
    switch (this.tabType) {
      case 'teacherComment':
        // this.getLessonListForParent();
        break;
      case 'teachPlan':
        this.loadTeachPlan();
        break;
      case 'teacherInfo':
        this.trainCourseTeacherInfoByClassId();
        break;
    }
  }

  /**
   * @author guoqs1331
   * @time 2018/1/30
   * @description 加载教学计划
   */
  loadTeachPlan() {
    this.fetchTeachScheme(this.classId);
    this.fetchClassroomSchedule(this.classId);
  }

  /**
   * @description
   * 根据班级ID获取 班级课时列表
   * @author @chenwh576
   * @time 2018.01.02
   * @param {number} classId
   * @return {Observable<SNSResult<TrainClassroomScheme>>}
   */
  fetchClassroomSchedule(classId: number): void {
    if (classId) {
      this._palnService.fetchClassroomSchedule(this.classId)
        .subscribe(res => {
          this.classSchedule = [...res.data];
        });
    }
  }

  /*
 * 切换tab 的显示全部与否
 */
  tabContentSwitch(i: number) {
    this.tabs[i].isShow = !this.tabs[i].isShow;
  }

  getIcon(name: string): string {
    return this._imgService.getIcon(name);
  }

  /**
   * @description
   * 根据班级ID获取教学计划
   * @author @chenwh576
   * @time 2018.01.02
   * @param {number} classId
   */
  fetchTeachScheme(classId: number) {
    this._palnService.fetchTeachScheme(classId)
      .subscribe(res => {
        this.teachScheme = res.data;

        const keys = Object.keys(this.teachScheme);
        this.tabs.forEach((item, index) => {
          keys.map((subItem, subindex) => {
            if (this.teachScheme[subItem] !== '' && Object.is(subItem, item['tag'])) {
              item.content = this.teachScheme[subItem];
            }
          });
        });
        this.tabContentHandler();
      });
  }

  /**
   * 判断 顶部tab 是否需要展开收起功能
   */
  tabContentHandler() {
    const tabs = this.tabs;
    for (let i = 0; i < 3; i++) {
      if (tabs[i].content.length > 110) {
        tabs[i].shortContent = tabs[i].content.slice(0, 111) + '...';
        tabs[i].hasExtend = true;
      }
    }
    this.tabs = tabs;
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 获取教练列表
   */
  trainCourseTeacherInfoByClassId() {
    this.parentService.trainCourseTeacherInfoByClassId(this.teacherCommentInfo.classId).subscribe((res) => {
      if (res['result'] === '0' && res.data) {
        this.teachers = res.data;
        // this.teachers = [...this.teachers];
        this.curTeacherInfo = this.teachers[0];
      }
    });
  }

  /**
   * @author guoqs1331
   * @time 2018/1/29
   * @description 选择教练
   */
  chooseTeacher(teacher, index) {
    this.teacherIndex = index;
    this.curTeacherInfo = this.teachers[index];
  }

  /**
   * @author guoqs1331
   * @time 2018/1/30
   * @description 查看点评
   */
  goLessonComment(lesson) {
    let nowTime = new Date().getTime();
    if (nowTime < lesson.beginDate) {
      this.toolService.showToast('未到上课时间，暂无点评');
      return;
    }
    if (lesson.state === 0) {
      this.toolService.showToast('该课时未销课，暂无点评');
      return;
    }
    let param = {
      scheduleId: lesson.scheduleId,
      studentId: this.teacherCommentInfo.studentId
    };
    this.trainService.updateRemarkReadState(param).subscribe();
    this.router.navigate(['/train/remark/parent/lesson'], {
      queryParams: {
        'studentId': this.teacherCommentInfo.studentId,
        'lessonId': lesson.scheduleId
      }
    });
  }

  /**
   * @author ouxh862
   * @time 2018/1/31
   * @description 跳到教案详情
   * @param {TrainClassScheduleVO} schedule
   * @param {number} i
   */
  goToPlanDetail(schedule: TrainClassScheduleVO, i: number) {
    const params = {
      subjectName: this.toolService.encodeUri('课时' + (i + 1) + ':' + schedule.subjectName),
      teacherName: this.toolService.encodeUri(schedule.teacherName ? schedule.teacherName : '')
    };
    this.router.navigate([`/train/plan/detail/${schedule.id}`], {queryParams: params});
  }

  ngOnInit() {
  }

}
